<!--  -->
<template>
  <div class="mistake-test js-clickbody" @click="bodyClick('body')">
    <div class="chose-course-top">
      <div class="header-left">
        <span class="back-arrow" @click="quitStudy"></span>
      </div>
      <div class="course-title">
        语法改错
      </div>
      <div class="btn-group">
        <div class="spend-time">
          <img src="~assets/reverse/time.png" alt="" />
          <span>{{ spent_time | HHmmssFilter }}</span>
        </div>
        <a @click="print">打印</a>
        <a @click="lastAnswer" v-if="+detail.last_id !== 0">上次答题</a>
        <a @click="goSkill">答题技巧</a>
      </div>
    </div>
    <div class="list-wrap scrolToMinView listen-scroll">
      <div class="content-wrap clear">
        <div class="article-content">
          <p
            class="article-paragraph"
            v-for="(paragraph, index) in content"
            :key="`paragraph-p-${index}`"
          >
            <span v-for="(word, i) in paragraph" :key="word + i">
              <template v-if="(/@([A-Za-z0-9]+['’]?[A-Za-z0-9]*)@/).test(word)">
                <wordMistake
                  @setCurIndex="setCurIndex"
                  :ref="'wms_'+i"
                  :index="i"
                  :word="word"
                  @currIndex="clickCurrIndex"
                  :answerResult="answerResult"
                  :curr="indexShow"
                  @confirmChange="reciveChange"
                ></wordMistake>
              </template>
              <template v-else>
                <span class="normal-blank">{{ word }}</span>
              </template>
            </span>
          </p>
        </div>
        <a-button
          v-if="+this.$route.query.num < 5"
          @click="submitAnswer"
          class="submit-btn"
          ghost
          type="primary"
          shape="round"
          >提交答案</a-button
        >
      </div>
    </div>
    <Timetips ref="timetips"></Timetips>
  </div>
</template>

<script>
import {
  grammarDetailInfo,
  subGrammarDetail,
  middleStop,
  checkWord,
  addWord,
  grammarExercisePrint,
} from "@/services/reverse";
import { SUCCESS_CODE } from "@/utils/const";
import { mapState, mapMutations } from "vuex";
import wordMistake from "./wordMistake";
import Timetips from "@/components/Timetips";
import $ from "jquery";
// fetchEndTime, validCode, proofreadSub
export default {
  name: "BlankDetail",
  components: {
    wordMistake,
    Timetips
  },
  data() {
    return {
      curIndex: 0,
      detail: {},
      content: [],
      spent_time: 0,
      timer: "",
      translate: {},
      answerIdList: [],
      answer: [],
      answerResult: {},
      indexShow: ''
    };
  },
  computed: {
    ...mapState({
      reverseStatus: (state) => state.reverseStatus,
    }),
  },
  watch: {},
  methods: {
    ...mapMutations(["setTranslateModal", "setGrammarSkill", "setGrammarBlankAnswer"]),
    fetchDetailInfo() {
      grammarDetailInfo({
        id: this.$route.query.id,
        type: this.$route.query.type,
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.detail = res.data;
          let article_title = res.data.question_content;
          let string = article_title.split(/\n/);
          this.content = string.map((v) => {
            return v
              .replace(/([A-Za-z0-9]+['’]?[A-Za-z0-9]*)/gi, " @$1@ ")
              .split(" ");
          });
        }
      });
    },
    replaceText(word) {
      const pattern = /[^a-zA-Z']/g;
      return word.replace(pattern, "");
    },
    checkWord(value) {
      checkWord({ word: this.replaceText(value) }).then((res) => {
        this.translate = res.data;
      });
    },
    addWord() {
      addWord({
        prototype_word: this.translate.prototype_word,
        select_word: this.translate.select_word,
        question_type: 3,
        is_diff: "0",
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("添加生词成功");
        }
      });
    },
    translateVoice() {
      let audio = document.getElementById("reverse-audio");
      audio.src = this.translate.project_voice;
      audio.play();
    },
    translateDetail() {
      this.setTranslateModal({
        visible: true,
        word: this.translate.select_word,
      });
      document.getElementById("app").click();
    },
    setCurIndex(index) {
      this.curIndex = index
    },
    clickCurrIndex(index) {
      console.log(index)
      this.indexShow = index
    },
    lastAnswer() {
      this.setGrammarBlankAnswer({
        visible: true,
        id: this.detail.last_id,
        type: 0
      })
      // this.$router.push({
      //   path: "/reverse/grammar-mistakeanswer",
      //   query: {
      //     id: this.detail.last_id,
      //     type: this.$route.query.type,
      //   },
      // });
    },
    print() {
      grammarExercisePrint({
        type: 5,
        id: this.detail.id,
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("已提交打印,请到管理平台进行打印");
        } else {
          this.$message.error("您打印的过于频繁，请休息一下");
        }
      });
    },
    goSkill() {
      this.setGrammarSkill({
        visible: true,
        type: "1",
        chapter_id: this.reverseStatus.chapters_id,
        curr_id: this.reverseStatus.curr_id,
      });
    },
    quitStudy() {
      this.$yxpConfirm({
        msg: "是否退出答题",
      })
        .then(() => {
          middleStop({
            question_type: 3,
            id: this.reverseStatus.chapters_id,
          });
          this.$router.go(-1);
        })
        .catch(() => {});
    },
    blankClick(id) {
      $(".answer-input")
        .eq(+id - 1)
        .find("input")
        .focus();
    },
    subBlankAnswer(answer) {
      subGrammarDetail({
        id: this.$route.query.id,
        type: "0",
        user_answer: JSON.stringify(answer),
      }).then((res) => {
        if (res.code === SUCCESS_CODE) {
          this.$message.success("提交成功");
          let last_id = res.data;
          this.$router.push({
            path: "/reverse/grammar-mistakeanswer",
            query: {
              id: last_id,
              isSub: true,
              type: this.$route.query.type,
            },
          });
        }
      });
    },
    reciveChange(obj) {
      if (typeof obj === "number") {
        delete this.answerResult[obj];
      } else {
        this.answerResult[obj.position] = obj;
      }
    },
    submitAnswer() {
      let result = Object.values(this.answerResult);
      result = result.map((v, i) => Object.assign(v, { id: i }));
      console.log(result);
      if (result.length <= 0) {
        this.$yxpConfirm({
          msg: "您还没有答题，是否提交",
        })
          .then(() => {
            this.subBlankAnswer(result);
          })
          .catch(() => {});
      } else {
        this.subBlankAnswer(result);
      }
    },
    bodyClick(e) {
      if (e === 'body') {
        this.indexShow = -1
      }
      if (!window[`bs:event:scroll:close`]) {
        this.indexShow = -1
      }
    },
  },
  created() {
    this.fetchDetailInfo();
  },
  mounted() {
    this.timer = setInterval(() => {
      this.spent_time++;
    }, 1000);
    document.querySelector('.listen-scroll').addEventListener('scroll', this.bodyClick, true)
  },
  beforeDestroy() {
    clearInterval(this.timer);
    document.querySelector('.listen-scroll').removeEventListener('scroll', this.bodyClick, true)
    this.$refs.timetips.stopTimer();
    this.$refs.timetips.stopEndTimer();
  },
};
</script>
<style lang="less" scoped>
/* @import url(); 引入公共css类 */
@import url("./test.less");
</style>
